<template>
  <div>
    <van-address-list
      v-model="chosenAddressId"
      :list="list"
      @add="onNewAddr"
      @edit="onEdit"
    />
  </div>
</template>
<script>
import { AddressList, Button } from "vant"
import { axios, API_URL } from "../../api"
export default {
  components: {
    [AddressList.name]: AddressList,
    [Button.name]: Button
  },
  data() {
    return {
      chosenAddressId: "1",
      list: []
    }
  },
  methods: {
    /* 编辑旧商品路由跳转 */
    onEdit() {
      let item = {}
      this.list.forEach(addr => {
        if (addr.id == this.chosenAddressId) {
          item = addr
        }
      })
      this.$router.push({
        name: "addrEdit",
        query: {
          editType: "editOldAddr",
          receiver: item.name,
          phone: item.tel,
          address: item.address,
          address_id: item.address_id
        }
      })
    },
    /* 添加新地址的路由跳转 */
    onNewAddr() {
      this.$router.push({
        name: "addrEdit",
        query: {
          editType: "addNewAddr"
        }
      })
    }
  },
  mounted: function() {
    axios
      .get(API_URL + "address", {
        headers: {
          authorization: this.$store.state.customer_token
        }
      })
      .then(response => {
        response.data.addrs.forEach((item, index) => {
          this.list.push({
            id: index,
            name: item.receiver,
            tel: item.phone,
            address: item.address,
            address_id: item.id
          })
        })
      })
      .catch(err => {
        if (err.response.status == 401) {
          this.$router.push({ name: "login" })
        }
        console.error(err)
      })
  }
}
</script>
